package demo8;

import java.io.Serializable;

/**
 * 懒汉式-静态内部类
 */
public class Singleton implements Serializable {

    private static boolean flag = false;
    // 私有构造方法
    private Singleton() {

        synchronized (Singleton.class) {
            if (flag) {
                throw new RuntimeException("不能创建多个对象");
            }
            // 将flag置为true
            flag = true;
        }
    }
    // 静态变量声明，并没有赋值
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // 反序列化时会自动调用该方法
    public Object readResolve() {
        return SingletonHolder.INSTANCE;
    }
}
